/*
 * To change this template, choose Tools | Templates and open the template in
 * the editor.
 */
package com.stip.server.da;

import com.stip.server.entities.Dorm;
import com.stip.server.entities.UsersInfo;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import javax.ejb.Stateless;
import javax.ejb.LocalBean;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

/**
 *
 * @author BlueBerry
 */
@Stateless
@LocalBean
public class DormDA {

    // Add business logic below. (Right-click in editor and choose
    // "Insert Code > Add Business Method")
@PersistenceContext 
EntityManager em;
public Dorm findDomByID(Integer id){
Dorm dorm=em.find(Dorm.class, id);
return dorm;
}
public Integer creatDorm(String dormName){
Dorm dorm=new Dorm();
dorm.setDormName(dormName);
em.persist(dorm);
em.flush();

List<UsersInfo> usersInfos=new ArrayList<UsersInfo>();
Query query=em.createQuery("SELECT u FROM UsersInfo u WHERE u.dorm = :dorm");
query.setParameter("dorm", dorm.getId());
List list=query.getResultList();
    for (Iterator it = list.iterator(); it.hasNext();) {
        UsersInfo object = (UsersInfo)it.next();
        usersInfos.add(object);
        
    }
dorm.setUsersInfoList(usersInfos);
em.merge(dorm);
return  dorm.getId();
}
public Boolean eidtDorm(String dormName,Integer id){
Dorm dorm=em.find(Dorm.class, id);
    if (dorm!=null) {
        if (dormName==null) {
            dorm.setDormName(dorm.getDormName());
        } else {
            dorm.setDormName(dormName);
        }
        em.merge(dorm);
        return  true;
    } else {
        return  false;
    }
}
public Boolean removeDorm(Integer id){
Dorm dorm=em.find(Dorm.class, id);
    if (dorm!=null) {
        em.remove(dorm);
        return  true;
    } else {
        return  false;
    }
}
}
